<template>

  <div class="table1_container">
    <div class="table1_dataShower" style="padding-bottom: 50px; padding-top: 50px; box-sizing: border-box">
      <button class="report-top-button" @click="back">返回上级页面</button>
      <button class="report-top-button" @click="print">打印报表</button>
      <div style="text-align: center; margin: 10px 0;">
        <div style="display: inline-flex; gap: 20px;">
          <!-- 未完成 -->
          <div style="display: flex; align-items: center;">
            <div
              style="width: 16px; height: 16px; background-color: #ffffff; border: 1px solid #ddd; margin-right: 5px;"
            />
            <span>未完成</span>
          </div>

          <!-- 已完成 -->
          <div style="display: flex; align-items: center;">
            <div
              style="width: 16px; height: 16px; background-color: #e6f7e6; border: 1px solid #ddd; margin-right: 5px;"
            />
            <span>已完成</span>
          </div>

          <!-- 不合格重采 -->
          <div style="display: flex; align-items: center;">
            <div
              style="width: 16px; height: 16px; background-color: #ffebeb; border: 1px solid #ddd; margin-right: 5px;"
            />
            <span>不合格重采</span>
          </div>
        </div>
      </div>
      <div class="fenxiang-normal-table">
        <h1>{{ (reportData && reportData.fenxiangName) || '' }}工程质量验收记录</h1>
        <span class="table1_reportId" style="text-align: right; display: block;margin-right:23%; margin-bottom: 5px;"> 编号： {{
            ' '
          }}</span>
        <table class="fenxiang-table1_top_table">
        <tr>
          <td colspan="3" style="font-weight: 700">单位（子单位）工程名称</td>
          <td colspan="5">{{ (reportData && reportData.subprojectName) || '' }}</td>
          <td colspan="3" style="font-weight: 700">分部（子分部）工程名称</td>
          <td colspan="5">{{ (reportData && reportData.fenbuProjectName) || '' }}</td>
        </tr>
        <tr>
          <td colspan="3" style="font-weight: 700">分项工程工程量</td>
          <td colspan="5">{{ (reportData && reportData.area) || '' }}</td>
          <td colspan="3" style="font-weight: 700">检验批数量</td>
          <td colspan="5">{{ (reportData && reportData.taskAmount) || '' }}</td>
        </tr>
        <tr>
          <td colspan="3" style="font-weight: 700">施工单位</td>
          <td colspan="4">{{ (reportData && reportData.projectName) || '' }}</td>
          <td colspan="2" style="font-weight: 700">项目负责人</td>
          <td colspan="3">{{ (reportData && reportData.shigongDirector) || '' }}</td>
          <td colspan="2" style="font-weight: 700">项目技术负责人</td>
          <td colspan="2">{{ (reportData && reportData.technicalDirector) || '' }}</td>
        </tr>
        <tr>
          <td colspan="3" style="font-weight: 700">分包单位</td>
          <td colspan="4">{{ getFenbaoDataProperty('fenbaoCompany') }}</td>
          <td colspan="2" style="font-weight: 700">分包单位项目负责人</td>
          <td colspan="3">{{ getFenbaoDataProperty('fenbaoDirector') }}</td>
          <td colspan="2" style="font-weight: 700">分包单位技术负责人</td>
          <td colspan="2">{{ getFenbaoDataProperty('fenbaoTechnical') }}</td>
        </tr>
        <tr>
          <td style="font-weight: 700">序号</td>
          <td colspan="3" style="font-weight: 700">检验批名称</td>
          <td colspan="3" style="font-weight: 700">检验批容量</td>
          <td colspan="3" style="font-weight: 700">部位/区段</td>
          <td colspan="3" style="font-weight: 700">施工单位检查结果</td>
          <td colspan="3" style="font-weight: 700">监理单位验收结论</td>
        </tr>

        <!--TODO for循环=======================================================-->
        <tr v-for="(item, index) in getReportDataArray()" :key="index">
          <td>{{ (item && item.inspectType) ? index + 1 : ' ' }}</td>
          <td colspan="3">{{ (item && item.inspectType) || '' }}</td>
          <td colspan="3">{{ (item && item.inspectVolume) || '' }}</td>
          <td colspan="3">{{ (item && item.inspectType) ? (item.inspectPart || '') : ' ' }}</td>
          <td colspan="3">{{ (item && item.inspectType) ? (item.checkResult || '') : ' ' }}</td>
          <td colspan="3">{{ (item && item.inspectType) ? (item.checkConclusion || '') : ' ' }}</td>
        </tr>
        <tr class="print-bottom1">
          <td style="height: 50px;text-align: left; padding-left: 10px;" colspan="16">
            说明：
          </td>
        </tr>
        <tr class="print-bottom2">
          <td rowspan="3" colspan="3" style="font-weight: 700">施工单位<br>检查结果</td>
          <td rowspan="3" colspan="7"></td>
          <td colspan="6" style="border-bottom-width: 0"/>
        </tr>
        <tr class="print-bottom2">
          <td colspan="6" style="border-top-width: 0;border-bottom-width: 0; font-weight: 700;">项目专业技术负责人：
          </td>
        </tr>
        <tr class="print-bottom2">
          <td colspan="6" style="border-top-width: 0;text-align: right; letter-spacing: 1em"> 年 月 日</td>
        </tr>

        <tr class="print-bottom2">
          <td rowspan="4" colspan="3" style="font-weight: 700">监理单位<br> 验收结论</td>
          <td rowspan="4" colspan="7"></td>
          <td colspan="6" style="border-bottom-width: 0"/>
        </tr>
        <tr class="print-bottom2">
          <td colspan="6" style="border-top-width: 0;border-bottom-width: 0; font-weight: 700">专业监理工程师：</td>
        </tr>
        <tr class="print-bottom2">
          <td colspan="6" style="border-top-width: 0;text-align: right; letter-spacing: 1em"> 年 月 日</td>
        </tr>
      </table>
      </div>
      <!-- 打印显示：分页格式（通过方法动态生成） -->
      <div class="fenxiang-pages" ref="fenxiangPagesContainer" style="display: none;"></div>
    </div>
  </div>
</template>

<script>
import { searchFenxiangCheckPreview } from '@/api/statementManage/yanShou/statementManage'

const PAGE_ROW_LIMIT = 12

export default {
  data() {
    return {
      localStorageId: '',
      reportData: {
        fenxiangName: '',
        subprojectName: '',
        fenbuProjectName: '',
        area: '',
        taskAmount: '',
        projectName: '',
        shigongDirector: '',
        technicalDirector: '',
        fenbaoData: {
          fenbaoCompany: '',
          fenbaoDirector: '',
          fenbaoTechnical: ''
        },
        data: []
      },
      previewData: {},
      receivedData: {},
      pageRowLimit: PAGE_ROW_LIMIT
    }
  },
  computed: {
    preparedItems() {
      const items = (this.getReportDataArray() || []).map(item => ({ ...item }))
      let serial = 1
      items.forEach(item => {
        if (item.inspectType) {
          item.__serial = serial++
        }
      })
      return items
    },
    pagedItems() {
      const pages = []
      let current = []
      let countedRows = 0
      const source = this.preparedItems

      source.forEach(item => {
        const isCountable = this.isCountableRow(item)
        if (isCountable && countedRows === this.pageRowLimit) {
          pages.push(current)
          current = []
          countedRows = 0
        }
        current.push(item)
        if (isCountable) {
          countedRows++
        }
      })

      if (current.length || pages.length === 0) {
        pages.push(current)
      }

      return pages
    }
  },
  methods: {
    // 安全访问fenbaoData的方法
    getFenbaoDataProperty(property) {
      if (this.reportData &&
        this.reportData.fenbaoData &&
        this.reportData.fenbaoData[property]) {
        return this.reportData.fenbaoData[property]
      }
      return ''
    },

    // 安全访问data数组的方法
    getReportDataArray() {
      if (this.reportData && Array.isArray(this.reportData.data)) {
        return this.reportData.data
      }
      return []
    },

    back() {
      this.$router.go(-1)
    },
    print() {
      // 在打印前生成分页HTML
      this.generatePagedHTML()
      window.print()
    },
    generatePagedHTML() {
      // 生成分页HTML的方法
      const container = this.$refs.fenxiangPagesContainer
      if (!container) return

      // 清空容器
      container.innerHTML = ''

      const pages = this.pagedItems
      const data = this.reportData

      pages.forEach((pageItems, pageIndex) => {
        const pageDiv = document.createElement('div')
        pageDiv.className = 'fenxiang-page'

        // 生成页面HTML
        let html = `
          <h1>${data.fenxiangName || ''}工程质量验收记录</h1>
          <span class="table1_reportId" style="text-align: right; display: block;margin-right:23%; margin-bottom: 5px;">编号： </span>
          <table class="fenxiang-table1_top_table">
            <tr>
              <td colspan="3" style="font-weight: 700">单位（子单位）工程名称</td>
              <td colspan="5">${data.subprojectName || ''}</td>
              <td colspan="3" style="font-weight: 700">分部（子分部）工程名称</td>
              <td colspan="5">${data.fenbuProjectName || ''}</td>
            </tr>
            <tr>
              <td colspan="3" style="font-weight: 700">分项工程工程量</td>
              <td colspan="5">${data.area || ''}</td>
              <td colspan="3" style="font-weight: 700">检验批数量</td>
              <td colspan="5">${data.taskAmount || ''}</td>
            </tr>
            <tr>
              <td colspan="3" style="font-weight: 700">施工单位</td>
              <td colspan="4">${data.projectName || ''}</td>
              <td colspan="2" style="font-weight: 700">项目负责人</td>
              <td colspan="3">${data.shigongDirector || ''}</td>
              <td colspan="2" style="font-weight: 700">项目技术负责人</td>
              <td colspan="2">${data.technicalDirector || ''}</td>
            </tr>
            <tr>
              <td colspan="3" style="font-weight: 700">分包单位</td>
              <td colspan="4">${this.getFenbaoDataProperty('fenbaoCompany')}</td>
              <td colspan="2" style="font-weight: 700">分包单位项目负责人</td>
              <td colspan="3">${this.getFenbaoDataProperty('fenbaoDirector')}</td>
              <td colspan="2" style="font-weight: 700">分包单位技术负责人</td>
              <td colspan="2">${this.getFenbaoDataProperty('fenbaoTechnical')}</td>
            </tr>
            <tr>
              <td style="font-weight: 700">序号</td>
              <td colspan="3" style="font-weight: 700">检验批名称</td>
              <td colspan="3" style="font-weight: 700">检验批容量</td>
              <td colspan="3" style="font-weight: 700">部位/区段</td>
              <td colspan="3" style="font-weight: 700">施工单位检查结果</td>
              <td colspan="3" style="font-weight: 700">监理单位验收结论</td>
            </tr>
        `

        // 生成数据行
        pageItems.forEach(item => {
          const serial = item.__serial || ''
          html += `
            <tr class="fenxiang-body-row">
              <td>${serial}</td>
              <td colspan="3">${item.inspectType || ''}</td>
              <td colspan="3">${item.inspectVolume || ''}</td>
              <td colspan="3">${item.inspectType ? (item.inspectPart || '') : ''}</td>
              <td colspan="3">${item.inspectType ? (item.checkResult || '') : ''}</td>
              <td colspan="3">${item.inspectType ? (item.checkConclusion || '') : ''}</td>
            </tr>
          `
        })

        // 添加占位行
        const counted = pageItems.filter(item => this.isCountableRow(item)).length
        const fillerCount = Math.max(this.pageRowLimit - counted, 0)
        for (let i = 0; i < fillerCount; i++) {
          html += `
            <tr class="fenxiang-body-row is-placeholder">
              <td></td>
              <td colspan="3"></td>
              <td colspan="3"></td>
              <td colspan="3"></td>
              <td colspan="3"></td>
              <td colspan="3"></td>
            </tr>
          `
        }

        // 生成验收区域
        html += `
            <tr class="print-bottom1">
              <td style="height: 30px;text-align: left; padding-left: 10px;" colspan="16">说明：</td>
            </tr>
            <tr class="print-bottom2">
              <td rowspan="3" colspan="3" style="font-weight: 700">施工单位<br>检查结果</td>
              <td rowspan="3" colspan="7"></td>
              <td colspan="6" style="border-bottom-width: 0"/>
            </tr>
            <tr class="print-bottom2">
              <td colspan="6" style="border-top-width: 0;border-bottom-width: 0; font-weight: 700;">项目专业技术负责人：</td>
            </tr>
            <tr class="print-bottom2">
              <td colspan="6" style="border-top-width: 0;text-align: right; letter-spacing: 1em"> 年 月 日</td>
            </tr>
            <tr class="print-bottom2">
              <td rowspan="4" colspan="3" style="font-weight: 700">监理单位<br> 验收结论</td>
              <td rowspan="4" colspan="7"></td>
              <td colspan="6" style="border-bottom-width: 0"/>
            </tr>
            <tr class="print-bottom2">
              <td colspan="6" style="border-top-width: 0;border-bottom-width: 0; font-weight: 700">专业监理工程师：</td>
            </tr>
            <tr class="print-bottom2">
              <td colspan="6" style="border-top-width: 0;text-align: right; letter-spacing: 1em"> 年 月 日</td>
            </tr>
          </table>
        `

        pageDiv.innerHTML = html
        container.appendChild(pageDiv)
      })
    },
    isCountableRow(item) {
      return !!(item && item.inspectType && !item.__placeholder)
    }
  },
  async mounted() { // 钩子函数
    try {
      this.receivedData = JSON.parse(sessionStorage.getItem('tempObj'))
      console.log('receivedData:', this.receivedData)

      if (this.receivedData && this.receivedData.subprojectId && this.receivedData.fenxiangId) {
        console.log('请求数据为， subprojectId:', this.receivedData.subprojectId, this.receivedData.fenxiangId)
        const { result } = await searchFenxiangCheckPreview(this.receivedData.subprojectId, this.receivedData.fenxiangId)
        console.log('API返回数据:', result)

        // 安全地更新reportData
        if (result) {
          this.reportData = {
            ...this.reportData, // 保留默认值
            ...result // 用API数据覆盖
          }
        }
      } else {
        console.error('缺少必要的参数: subprojectId 或 fenxiangId')
      }
    } catch (error) {
      console.error('数据加载失败:', error)
    }
  },
  beforeDestroy() { // 离开页面要做的事
    if (this.localStorageId) {
      localStorage.removeItem(this.localStorageId)
    }
    document.querySelector('body').setAttribute('style', 'background-color: white;')
  },
  beforeCreate() {
    document.querySelector('body').setAttribute('style', 'background-color:#f5f5f5;')
  }
}
</script>

<style>
@import '../../../../assets/css/yanshou/fenxiangCheck.css';

/*
先来设置每个任务项对应的背景颜色吧！
 */
.row-unfinished {
  background-color: #ffffff; /* 未完成 - 白色或默认色 */
}

.row-finished {
  background-color: #e6f7e6; /* 已完成 - 浅绿色 */
}

.row-failed {
  background-color: #ffebeb; /* 不合格重采 - 浅红色 */
}

.table1_container {
  width: 70%;
  background: white;
  margin-left: auto;
  margin-right: auto;
  text-align: center;
  padding-bottom: 20px;
}

.table1_dataShower {
  width: 80%;
  background: white;
  margin: 0 auto;
  border: 2px black solid;
}

/*这是返回按钮的样式*/
.report-top-button {
  display: block;
  margin: 0 auto;
  margin-bottom: 20px;
  padding: 12px 28px;
  font-size: 16px;
  font-weight: 600;
  font-family: 'Arial', sans-serif;
  color: #ffffff;
  background: linear-gradient(90deg, #1e3a8a, #3b82f6); /* 建筑行业蓝色调，稳重且有活力 */
  border: none;
  border-radius: 6px;
  cursor: pointer;
  transition: all 0.3s ease;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
}

.report-top-button:hover {
  background: linear-gradient(90deg, #1e3a8a, #2563eb);
  box-shadow: 0 4px 8px rgba(0, 0, 0, 0.15);
  transform: translateY(-1px);
}

.report-top-button:active {
  box-shadow: 0 1px 2px rgba(0, 0, 0, 0.1);
  transform: translateY(0);
}

/*表格样式*/
.fenxiang-table1_top_table {
  width: 90%;
  margin: 0 auto;
  border-collapse: collapse;
  border: 1px solid black;
}

/*表格的样式*/
.fenxiang-table1_top_table tr td {
  height: 70px;
  border: 1px solid black;
  word-wrap: break-word; /* 允许长单词换行 */
  overflow-wrap: break-word; /* 更现代的换行属性 */
}

#table1_top_table_last_col {
  width: 20%;
  min-height: 50px;
}

th {
  box-sizing: border-box !important;
}

.print-bottom2 {
  height: 50px !important;
}

/* 正常显示：原表格 */
.fenxiang-normal-table {
  display: block;
}

/* 打印显示：分页格式 - 正常时隐藏 */
.fenxiang-pages {
  display: none;
  width: 100%;
}

.fenxiang-page {
  margin-bottom: 30px;
  page-break-after: none;
}

.fenxiang-page:last-child {
  margin-bottom: 0;
}

.fenxiang-body-row td {
  height: 48px;
  min-height: 48px;
}

/* 非打印模式下隐藏占位行 */
.fenxiang-body-row.is-placeholder {
  display: none;
}

@media print {
  @page {
    size: A4 portrait;
  }

  .table1_dataShower {
    padding: 0 !important;
  }

  /* 打印时隐藏原表格 */
  .fenxiang-normal-table {
    display: none !important;
  }

  /* 打印时显示分页视图 */
  .fenxiang-pages {
    display: block !important;
    width: 100% !important;
  }

  .fenxiang-page {
    display: block !important;
    margin-bottom: 0;
    /* 打印模式下启用分页 */
    page-break-after: always;
    width: 100% !important;
  }

  .fenxiang-page:last-child {
    page-break-after: auto;
  }

  /* 打印模式下显示占位行 */
  .fenxiang-body-row.is-placeholder {
    display: table-row !important;
  }

  .fenxiang-body-row.is-placeholder td {
    color: transparent;
  }

  .fenxiang-table1_top_table {
    width: 100% !important;
    max-width: 100% !important;
  }

  /* 调整说明行和验收区域的高度 */
  .print-bottom1 {
    height: 30px !important;
  }

  .print-bottom1 td {
    height: 30px !important;
    min-height: 30px !important;
  }

  .print-bottom2 {
    height: 8px !important;
  }

  .print-bottom2 td {
    height: 8px !important;
    min-height: 8px !important;
  }
}
</style>
